<?php // $Id: export.php, 2010/08/30 Afterlastangel $


//  Lists all the sessions for a course

require_once('../../config.php');
require_once('locallib.php');
require_once('export_form.php');

$id 	= required_param('id', PARAM_INT);

if (! $cm = get_record("course_modules", "id", $id)) {
    error("Course Module ID was incorrect");
}

if (! $course = get_record("course", "id", $cm->course)) {
    error("Course is misconfigured");
}

if (! $diemrenluyen = get_record('diemrenluyen', 'id', $cm->instance)) {
    error("Course module is incorrect");
}

require_login($course->id);

$context = get_context_instance(CONTEXT_MODULE, $cm->id);
//Can quyen export diem
require_capability('mod/diemrenluyen:export', $context);
//Tao lay thong tin form gui den - dung thay the
$mform_export = new mod_diemrenluyen_export_form('export.php', array('course'=>$course, 'cm'=>$cm, 'modcontext'=>$context));
if ($fromform = $mform_export->get_data()) {
//    print_r($fromform);
    $group = groups_get_group($fromform->group);
    if ($group) {
        $students = get_users_by_capability($context, 'moodle/legacy:student', '', 'u.lastname ASC', '', '', $group->id, '', false);
    } else {
        $students = get_users_by_capability($context, 'moodle/legacy:student', '', 'u.lastname ASC', '', '', '', '', false);
    }
    if ($students) {
        $drl_month = date("m",$fromform->sessionenddate);
        $drl_year =  date("Y",$fromform->sessionenddate);
        $filename = clean_filename($course->shortname.'_diemrenluyen_'.userdate(time(), '%Y%m%d-%H%M'));
        $data->tabhead = array();
            $data->course = $course->fullname;
            $data->group = $group ? $group->name : get_string('allparticipants');
            $data->tabhead[] = get_string('studentid','diemrenluyen');
            $data->tabhead[] = get_string('username');
            $data->tabhead[] = get_string('firstname');
            $data->tabhead[] = get_string('lastname');
            
            $data->tabhead[] = get_string("dieu1","diemrenluyen");
            $data->tabhead[] = get_string("dieu2","diemrenluyen");
            $data->tabhead[] = get_string("dieu3","diemrenluyen");
            $data->tabhead[] = get_string("dieu4","diemrenluyen");
            $data->tabhead[] = get_string("dieu5","diemrenluyen");
            $data->tabhead[] = get_string("total","diemrenluyen");
            $data->tabhead[] = get_string("type","diemrenluyen");
            $data->tabhead[] = get_string("Marked by","diemrenluyen");
        $data->table = array();
            $i = 0;
            foreach($students as $student) {
//                id nay co the duoc thay the boi ID lay tu dia chi email cua sinh vien.
                $data->table[$i][] = $student->id;
                $data->table[$i][] = $student->username;
                $data->table[$i][] = $student->lastname;
                $data->table[$i][] = $student->firstname;
                $total_mark=0; //Tong diem ren luyen tung thang cua sinh vien

                if ($rec = get_record('diemrenluyen_sinhvien', 'diemrenluyenid', $diemrenluyen->id, 'userid', $student->id,'month',mktime(0, 0, 0, $drl_month, 1, $drl_year))) {
                    for ($jj=1;$jj<=5;$jj++){
                        $drl_mark = "d" . $jj;
                        $data->table[$i][] = $rec->$drl_mark;
                        $total_mark += intval($rec->$drl_mark);
                    }
                    $data->table[$i][] = $total_mark;
                    $data->table[$i][] = xeploai($total_mark);
                    if (!$teacher_cache[$rec->takenby])
                    {
                        if ($teacher = get_record('user', 'id', $rec->takenby)) {
                            $teacher_cache[$rec->takenby] = fullname($teacher);
                       }
                    }
                    $data->table[$i][] = $teacher_cache[$rec->takenby];
                } else {
                    for ($jj=1;$jj<=5;$jj++){
                        $data->table[$i][] = '-';
                    }
                }
               
                $i++;
            }
//            Chon phuong thuc export ra CVS - OpenOffice, hoac Excel
            if ($fromform->format === 'text') {
                    ExportToCSV($data, $filename);

            } else {
                    ExportToTableEd($data, $filename, $fromform->format);
            }
            exit;
    }
} else
    {
        /// Print headers
        $strdiemrenluyens = get_string('modulenameplural', 'diemrenluyen');
        $strdiemrenluyen  = get_string('modulename', 'diemrenluyen');
        $navlinks = array();
        $navlinks[] = array('name' => $strdiemrenluyens, 'link' => "index.php?id=$course->id", 'type' => 'activity');
        $navlinks[] = array('name' => format_string($diemrenluyen->name), 'link' => '', 'type' => 'activityinstance');

        $navigation = build_navigation($navlinks);

        print_header_simple(format_string($diemrenluyen->name), '', $navigation, '', '', true,
              update_module_button($cm->id, $course->id, $strdiemrenluyen), navmenu($course, $cm));
        show_tabs($cm, $context, 'export');
        $mform_export->display();
    }
print_footer($course);

function ExportToTableEd($data, $filename, $format) {
	global $CFG;

    if ($format === 'excel') {
	    require_once("$CFG->libdir/excellib.class.php");
	    $filename .= ".xls";
	    $workbook = new MoodleExcelWorkbook("-");
    } else {
	    require_once("$CFG->libdir/odslib.class.php");
	    $filename .= ".ods";
	    $workbook = new MoodleODSWorkbook("-");
    }
/// Sending HTTP headers
    $workbook->send($filename);
/// Creating the first worksheet
    $myxls =& $workbook->add_worksheet('Attendances');
/// format types
    $formatbc =& $workbook->add_format();
    $formatbc->set_bold(1);

    $myxls->write(0, 0, get_string('course'), $formatbc);
    $myxls->write(0, 1, $data->course);
    $myxls->write(1, 0, get_string('group'), $formatbc);
    $myxls->write(1, 1, $data->group);

    $i = 3;
    $j = 0;
    foreach ($data->tabhead as $cell) {
    	$myxls->write($i, $j++, $cell, $formatbc);
    }
    $i++;
    $j = 0;
    foreach ($data->table as $row) {
    	foreach ($row as $cell) {
    		$myxls->write($i, $j++, $cell);
    	}
		$i++;
		$j = 0;
    }
	$workbook->close();
}

function ExportToCSV($data, $filename) {
    $filename .= ".txt";

    header("Content-Type: application/download\n");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Pragma: public");

    echo get_string('course')."\t".$data->course."\n";
    echo get_string('group')."\t".$data->group."\n\n";

    echo implode("\t", $data->tabhead)."\n";
    foreach ($data->table as $row) {
    	echo implode("\t", $row)."\n";
    }
}
?>
